﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Sugar;
using Telerik.Web.UI;

namespace Medianamik.UI.TypeManagement
{
    public partial class PropertyList : BaseTypePage
    {
        private Guid? _typeID;  //Param obligatoire

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!StringHelper.IsGuid(Request.QueryString[DefaultParamNames.TypeID], ref _typeID) || CurrentType == null)
            {
                Response.Redirect(ReturnURL);
            }

            if (!IsPostBack)
            {
                grdProps.DataBind();
                LoadBreadcrumbs();
            }
        }

        protected void grdProps_ItemDataBound(object sender, GridItemEventArgs e)
        {
            var property = e.Item.DataItem as NodeTypeProperty;
            if (property != null)
            {
                SetRowPropertyStyle(e.Item, property.TypeID);

                //Gérer les propriétés héritées ou ManyToMany
                var edit = e.Item.FindControl("btnEditProperty") as HyperLink;
                if (property.TypeID != CurrentType.ID)
                {
                    //Appliquer les styles et désactiver les boutons

                    if (edit != null)
                        edit.Enabled = false;

                    var delete = e.Item.FindControl("btnDeleteProperty") as ImageButton;
                    if (delete != null)
                        delete.Enabled = false;
                }
                else if(edit != null && CameFromSearchPage)
                {
                    edit.NavigateUrl = GetSearchURL(edit.NavigateUrl);
                }
            }
        }

        protected void grdProps_ItemCommand(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "DeleteProperty":
                    //TODO: Vérifier que la propriété peut être supprimée
                    NodeTypeManager.DeleteTypeProperty(new Guid(e.CommandArgument.ToString()));

                    //Refresh CurrentType and properties
                    _currentType = null;

                    grdProps.Rebind();
                    break;
                default: 
                    break;
            }
        }

        protected void grdProps_RowDrop(object sender, GridDragDropEventArgs e)
        {
            if (e.DestDataItem != null)
            {
                CurrentType.MoveProperty((Guid) e.DraggedItems[0].GetDataKeyValue("ID")
                                         , (Guid) e.DestDataItem.GetDataKeyValue("ID")
                                         ,
                                         e.DropPosition == GridItemDropPosition.Above
                                             ? DropPosition.Above
                                             : DropPosition.Below);

                NodeTypeManager.SaveType(CurrentType);
                grdProps.Rebind();
            }
        }

        protected void grdProps_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            grdProps.Visible = true;

            //On crée un DataSource avec les Properties et les ManyToManyRelations pour les afficher dans la même liste
            //Cela permet l'ordonnancement de toutes les propriétés d'un Noeud
            grdProps.DataSource = CurrentType.GetAllPropertiesWithManyToManyRelations()
                .OrderBy(p=> CurrentType.GetPropertyPosition(p.ID));
        }

        protected void OnPropertyVisibleStatusChanged(object sender, CommandEventArgs e)
        {
            CurrentType.SetPropertyVisibility(new Guid(e.CommandArgument.ToString()),
                e.CommandName.ToLower() == "activate");
            NodeTypeManager.SaveType(CurrentType);
            grdProps.Rebind();
        }

        private NodeType _currentType;
        public NodeType CurrentType
        {
            get
            {
                if (_currentType == null && _typeID.HasValue)
                {
                    _currentType = NodeTypeManager.GetNodeType(_typeID.Value);
                }

                return _currentType;
            }
        }

        private string _returnURL;
        public string ReturnURL
        {
            get
            {
                if (_returnURL == null)
                {
                    if (CameFromSearchPage)
                    {
                        _returnURL = SearchURL;
                    }
                    else
                    {
                        _returnURL = "TypeList.aspx";

                        if (CurrentType != null)
                            _returnURL += "?basetypeid=" + CurrentType.ID;
                    }
                }

                return _returnURL;
            }
        }

        private string _addURL;
        public string AddURL
        {
            get
            {
                if (_addURL == null && CurrentType != null)
                {
                    _addURL = "propertymanagement.aspx?" + Medianamik.Core.DefaultParamNames.TypeID + "=" + CurrentType.ID.ToString();
                }

                return _addURL;
            }
        }

        protected bool IsVisible(Guid propertyId)
        {
            return CurrentType.PropertyIsVisible(propertyId);
        }

        protected void SetRowPropertyStyle(WebControl pControl, Guid pTypeID)
        {
            if (!pTypeID.Equals(CurrentType.ID))
            {
                //pControl.CssClass = "ElementInactif " + pControl.CssClass ;
            }
        }

        private void LoadBreadcrumbs()
        {
            if (CameFromSearchPage)
            {
                bctFilAriane.Breadcrumbs = new List<Breadcrumb>
                                              {
                                                  new Breadcrumb(null, Resources("Medianamik_Global", "SearchBox_SearchLabel")),
                                                  new Breadcrumb(CurrentType.ID.ToString(), CurrentType.Name)
                                              };
                bctFilAriane.Url = ReturnURL;
            }
            else
            {
                List<Breadcrumb> breadcrumbs = CurrentType.Breadcrumbs.ToList();
                breadcrumbs.Insert(0, new Breadcrumb(null,
                                                     Resources("Medianamik_TypeManagement", "TypeManagement")));
                bctFilAriane.Breadcrumbs = breadcrumbs.AsEnumerable();
            }
            bctFilAriane.DataBind();
        }

        protected string GetLookupInfo(NodeTypeProperty property)
        {
            string result = "&nbsp;";

            if (property.IsLookup)
            { 
                if(property.PrimaryTypeID.HasValue)
                    result = NodeTypeManager.GetNodeType(property.PrimaryTypeID.Value).Name;
                else
                    result = NodeTypeManager.GetNodeType(property.TypeID).Name;
            }

            return result;
        }
    }
}